#!/usr/bin/python
# -*- coding: UTF-8 -*-



import os
import re
import time
import random
import math
import filetype
import psutil
import ctypes 
import subprocess
import sys
import shutil


WORD_WIDTHS=[(126,1),(159,0),(687,1),(710,0),(711,1),(727,0),(733,1),(879,0),(1154,1),(1161,0),(4347,1),(4447,2),(7467,1),(7521,0),(8369,1),(8426,0),(9000,1),(9002,2),(11021,1),(12350,2),(12351,1),(12438,2),(12442,0),(19893,2),(19967,1),(55203,2),(63743,1),(64106,2),(65039,1),(65059,0),(65131,2),(65279,1),(65376,2),(65500,1),(65510,2),(120831,1),(262141,2),(1114109,1),]

COLORS_NAME = ['aliceblue','antiquewhite','aqua','aquamarine','azure','beige','bisque','black','blanchedalmond','blue','blueviolet','brown','burlywood','cadetblue','chartreuse','chocolate','coral','cornflowerblue','cornsilk','crimson','cyan','darkblue','darkcyan','darkgoldenrod','darkgray','darkgreen','darkkhaki','darkmagenta','darkolivegreen','darkorange','darkorchid','darkred','darksalmon','darkseagreen','darkslateblue','darkslategray','darkturquoise','darkviolet','deeppink','deepskyblue','dimgray','dodgerblue','firebrick','floralwhite','forestgreen','fuchsia','gainsboro','ghostwhite','gold','goldenrod','gray','green','greenyellow','honeydew','hotpink','indianred','indigo','ivory','khaki','lavender','lavenderblush','lawngreen','lemonchiffon','lightblue','lightcoral','lightcyan','lightgoldenrodyellow','lightgreen','lightgray','lightpink','lightsalmon','lightseagreen','lightskyblue','lightslategray','lightsteelblue','lightyellow','lime','limegreen','linen','magenta','maroon','mediumaquamarine','mediumblue','mediumorchid','mediumpurple','mediumseagreen','mediumslateblue','mediumspringgreen','mediumturquoise','mediumvioletred','midnightblue','mintcream','mistyrose','moccasin','navajowhite','navy','oldlace','olive','olivedrab','orange','orangered','orchid','palegoldenrod','palegreen','paleturquoise','palevioletred','papayawhip','peachpuff','peru','pink','plum','powderblue','purple','red','rosybrown','royalblue','saddlebrown','salmon','sandybrown','seagreen','seashell','sienna','silver','skyblue','slateblue','slategray','snow','springgreen','steelblue','tan','teal','thistle','tomato','turquoise','violet','wheat','white','whitesmoke','yellow','yellowgreen']

IMG_EXTENSIONS = [
    '.jpg', '.JPG', '.jpeg', '.JPEG',
    '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tiff'
]

# 获取当前时间字符串
def get_current_time():    
    return psutil.datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def get_file_suffix(file):
    '''
    功能: 取文件名后缀
    参数:
        file:文件名
    返回: 文件扩展名(含.)
    '''
    return os.path.splitext(file)[-1]


def is_image_file(filename):
    #判断是否是图像文件
    return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)

#获取当前工作目录
def getcurpath():
    return os.path.dirname(__file__) if "__file__" in locals() else os.getcwd()
#判断目录是否存在，不存在就创建
def dir_is_exist(dir):
    if not os.path.exists(dir):
       os.makedirs(dir)
    return dir


#检测文件类型并返回
def check_file_type(filename):
    kind = filetype.guess(filename)
    if kind is None:
        return None
    return kind.mime.split('/')[0]

def detect_file_type(file_path: str) -> str:
    """
    检测文件类型并返回

    参数：
    file_path (str): 文件路径

    返回：
    str: 文件类型
    """
    import mimetypes
    # 使用mimetypes模块获取文件类型
    file_type = mimetypes.guess_type(file_path)[0]
    return file_type

#计算一个字符宽度
def get_width(o):
    global  WORD_WIDTHS
    o=ord(o)
    if o==0xe or o==0xf: return 0
    for num,wid in WORD_WIDTHS:
        if o<=num: return wid
    return 1

def get_char_width(char: str) -> int:
    """
    计算一个字符的宽度，包括汉字。

    参数：
        char (str): 输入的字符。

    返回：
        int: 字符的宽度。
    """
    import unicodedata

    width = unicodedata.east_asian_width(char)
    if width in ('F', 'W'):
        return 2
    else:
        return 1


def get_screen_resolution():
    """
    获取屏幕分辨率

    返回值：
        tuple: (宽度， 高度)
    """
    import subprocess

    try:
        output = subprocess.check_output("xrandr | grep '*' | awk '{print $1}'", shell=True).decode('utf-8').strip()
        resolution = output.split()[0].split('x')
        width, height = int(resolution[0]), int(resolution[1])
        return width, height
    except Exception as e:
        print(f"获取屏幕分辨率失败： {e}")
        return None


def get_screen_size():
    """
    获取屏幕尺寸
    :return: (width, height) 屏幕宽度和高度
    """
    size = os.get_terminal_size()
    return size.columns, size.lines



# #ffffff⇔(255,255,255)
def color(value): 
    """
    十六进制颜色代码与RGB元组相互转换

    参数：
        value (str or tuple):
            十六进制颜色代码，如'#FF5733'
            RGB元组，如(255,255,234)
    返回值：
        tuple: 一个包含三个整数的元组，分别表示红、绿、蓝三个通道的值，范围为0-255
        或
        
        str:            十六进制颜色代码，如'#FF5733'
            范围为[0-9a-fA-F]
    """
    digit = list(map(str, range(10))) + list("ABCDEF")
    if isinstance(value, tuple):
        string = '#'
        for i in value:
            a1 = i // 16
            a2 = i % 16
            string += digit[a1] + digit[a2]
        return string
    elif isinstance(value, str):
        if len(value) != 7 or value[0] != '#':
            return None
        try:
            a1 = digit.index(value[1]) * 16 + digit.index(value[2])
            a2 = digit.index(value[3]) * 16 + digit.index(value[4])
            a3 = digit.index(value[5]) * 16 + digit.index(value[6])
            return (a1, a2, a3)
        except ValueError:
            return None
            
def hex_to_rgb(hex_color: str) -> tuple:
    """
    将十六进制颜色代码转换为RGB元组

    参数：
        hex_color (str): 十六进制颜色代码，如'#FF5733'

    返回值：
        tuple: 一个包含三个整数的元组，分别表示红、绿、蓝三个通道的值，范围为0-255
    """
    # 去掉颜色代码前面的'#'
    hex_color = hex_color.lstrip('#')

    # 将十六进制颜色代码分解为红、绿、蓝三个通道的十六进制值
    red_hex = hex_color[0:2]
    green_hex = hex_color[2:4]
    blue_hex = hex_color[4:6]

    # 将十六进制值转换为十进制值
    red = int(red_hex, 16)
    green = int(green_hex, 16)
    blue = int(blue_hex, 16)

    return red, green, blue


def rgb_to_hex(rgb: tuple) -> str:
    """
    将RGB元组转换为十六进制颜色代码

    参数：
        rgb (tuple): 一个包含三个整数的元组，分别表示红、绿、蓝三个通道的值，范围为0-255

    返回值：
        str: 十六进制颜色代码，如'#FF5733'
    """
    red, green, blue = rgb

    # 将十进制值转换为十六进制值，并补齐两位
    red_hex = "{:02X}".format(red)
    green_hex = "{:02X}".format(green)
    blue_hex = "{:02X}".format(blue)

    # 拼接十六进制颜色代码
    hex_color = "#{}{}{}".format(red_hex, green_hex, blue_hex)

    return hex_color

#在当前目录下，新建一文件夹，如存在，则直接返回完整路径
def get_cur_dir(new_dir):
    cur_path = os.getcwd().replace('\\','/')    # 获取当前路径
    cur_path=os.path.join(cur_path,new_dir)
    if not os.path.exists(cur_path):
        os.mkdir(cur_path)
    return cur_path
    
#返回上一级目录
def get_pre_dir(mark):
    '''
    mark
    ----
    "." :当前目录
    "../" :上一层目录
    "../.." :上上层目录
    
    '''
    return os.path.abspath(os.path.join(os.getcwd(), mark))


#检查文件名及扩展名是否规范
def check_file_name(file_name):
    rule=r"^([\w\u4e00-\u9fa5]+)+[.]{1}[\w\u4e00-\u9fa5]{1,4}$"
    #rule=r"^([\w\u4e00-\u9fa5]{1,255})+[.]{1}[\w\u4e00-\u9fa5]{1,4}$"
    res=re.fullmatch(rule,file_name,re.I)
    if res == None:
        return None
    else:
        return res.group()
        
def check_filename(filename: str) -> bool:
    """
    检查文件名及扩展名是否规范。

    参数：
    - filename (str): 要检查的文件名。

    返回值：
    - bool: 如果文件名及扩展名规范，则返回True，否则返回False。
    """
    import re

    # 使用正则表达式匹配文件名，允许字母、数字、下划线、点号和短横线
    pattern = re.compile(r'^[\w\-\.]+$')

    # 提取文件名的扩展名
    extension = filename.split('.')[-1]

    # 检查文件名是否符合规范
    if not pattern.match(filename[:-len(extension)]):
        return False

    # 检查扩展名是否符合规范（至少有一个字符）
    if len(extension) == 0:
        return False

    return True

#检查邮箱地址是否合理
def iseMail(addr):
    rule=r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
    res=re.fullmatch(rule,addr,re.I)
    if res == None:
        return None
    else:
        return res.group()

def is_valid_email(email: str) -> bool:
    """
    检查邮箱地址是否合理

    参数：
    email (str): 需要检查的邮箱地址

    返回：
    bool: 如果邮箱地址合理，返回True，否则返回False
    """
    # 使用正则表达式匹配邮箱地址格式
    pattern = r'^[\w\.-]+@[\w.-]+\.\w+$'
    if re.match(pattern, email):
        return True
    else:
        return False

    
#返回一串随机数
def get_random_num():
    num=str(int(time.time())) + str(random.randint(100, 999))
    return num
    
#返回一串随机数文件名并检查为规范则返回，否则返回None
def get_random_file_name(ext):
    file_name=get_random_num()+"."+ext
    return check_file_name(file_name)
    
#返回文件保存的完整路径
def get_save_path(new_dir,ext):
    cur_path=get_cur_dir(new_dir)
    file_name=get_random_file_name(ext)
    assert file_name != None ,f"请检查参数{new_dir}、{ext}是否正确?"
    save_path=os.path.join(cur_path,file_name)
    return save_path


def plt_imshow(x, ax=None, show=True):
    if ax is None:
        fig, ax = plt.subplots()
    ax.imshow(x)
    ax.axis("off")
    if show: plt.show()
    return ax
    
#安装导入库
def install_and_import(package):
    try:
        __import__(package)
    except ImportError:
        print(f"正在安装 {package}...")
        subprocess.check_call([sys.executable, "-m", "pip", "install","-i","https://pypi.tuna.tsinghua.edu.cn/simple",package])
        __import__(package)



# 加载dll或so模块文件
def load_library(file_path):
    """
    加载dll或so模块文件

    参数：
    file_path (str): dll或so模块文件的路径

    返回：
    ctypes.CDLL: 加载后的模块对象
    """
    return ctypes.CDLL(file_path)

# 调用dll或so模块文件中的函数
def call_function(library, function_name, *args):
    """
    调用dll或so模块文件中的函数

    参数：
    library (ctypes.CDLL): 加载后的模块对象
    function_name (str): 要调用的函数名
    *args: 函数的参数列表

    返回：
    返回值类型取决于被调用的函数
    """
    function = getattr(library, function_name)
    return function(*args)

#查看模块中的函数及属性
def list_module_functions_and_attributes(module):
    """
    查看给定模块中的函数及属性。

    参数：
        module (str): 需要查看的模块名称，例如：'os', 'sys', 'math'等。

    返回值：
        list: 包含给定模块中所有函数和属性名称的列表。
    """
    import builtins
    # 导入指定模块
    try:
        mod = __import__(module)
    except ImportError:
        print(f"无法导入模块：{module}")
        return []

    # 获取模块中的函数及属性
    functions_and_attributes = [name for name in dir(mod) if not name.startswith('__')]

    return functions_and_attributes




def is_connected_by_dns(dns="8.8.8.8",port=53) -> bool:
    """
    判断当前计算机是否连接到互联网。
    参数:
        dns: 外网DNS服务器
        port: 端口
    返回值：
        bool: 如果已连接到互联网，则返回True，否则返回False。
    """
    import socket
    try:
        # 尝试连接到Google的DNS服务器（8.8.8.8）的端口53
        socket.create_connection((dns, port), timeout=3)
        return True
    except OSError:
        return False



def is_connected_by_url(Website="www.baidu.com"):
    """
    使用ping命令检查是否可以访问百度网站。
    参数:
        website: 网站
    返回：
        bool: 如果可以访问百度网站，则返回True，否则返回False。
    """
    import subprocess

    try:
        # 使用ping命令检查是否可以访问百度网站
        response = subprocess.run(['ping', '-c', '1', website], stdout=subprocess.PIPE)
        # 如果返回码为0，表示可以访问百度网站
        if response.returncode == 0:
            return Tr
        else:
            return False
    except Exception as e:
        print(f"发生错误： {e}")
        return False



def is_valid_ip(ip_str):
    """
    判断字符串是否是合理的IP地址

    参数：
    ip_str (str): 待判断的字符串

    返回：
    bool: 如果字符串是合理的IP地址，返回True，否则返回False
    """
    # 使用正则表达式匹配IP地址
    pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$'
    if re.match(pattern, ip_str):
        return True
    else:
        return False


def detect_color_code(string):
    """
    #ffffff <=> rgb(255,255,255)
    """
    if not string:
        return None
    if string.startswith('#') and len(string) == 7:
        try:
            int(string[1:], 16)
            return 'hex'
        except ValueError:
            pass
    elif string.startswith('rgb(') and string.endswith(')'):
        parts = [p.strip() for p in string[4:-1].split(',')]
        if len(parts) != 3:
            return None
        try:
            r, g, b = [int(p) for p in parts]
            if not all([(0 <= v <= 255) for v in (r, g, b)]):
                return None
            return 'rgb'
        except ValueError:
            pass
    return None



def is_chinese_char(char: str) -> bool:
    """
    判断给定的字符是否是汉字

    参数：
    char (str): 需要判断的字符，长度为1

    返回值：
    bool: 如果字符是汉字，返回True，否则返回False
    """
    # 汉字的Unicode编码范围是0x4E00-0x9FA5
    return 0x4E00 <= ord(char) <= 0x9FA5





def is_valid_url(url):
    """
    判断给定的字符串是否是合理的链接地址。

    参数：
        url (str): 待判断的字符串。

    返回：
        bool: 如果字符串是合理的链接地址，返回True；否则返回False。
    """
    # 定义URL的正则表达式
    regex = re.compile(
        r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
    )

    # 使用正则表达式匹配字符串
    if regex.match(url):
        return True
    else:
        return False




def IsColor(color_code: str) -> bool:
    """
    检测颜色代码字符串是否合理

    参数：
        color_code (str): 颜色代码字符串，如#ef0078,#dff

    返回：
        bool: True表示合理，False表示不合理
    """
    pattern = r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$'
    if re.match(pattern, color_code):
        return True
    else:
        return False




def get_color_info_cn(color_name):
    """
    根据给定的颜色名称，返回对应的英文名称和十六进制颜色代码。
    
    参数：
    color_name (str): 颜色名称，例如 "红色"、"橙色" 等。
    
    返回值：
    tuple: 包含两个元素的元组，第一个元素是颜色英文名称 (str)，第二个元素是十六进制颜色代码 (str)。
    """
    color_dict = {
        "红色": ("red", "#FF0000"),
        "橙色": ("orange", "#FFA500"),
        "黄色": ("yellow", "#FFFF00"),
        "绿色": ("green", "#008000"),
        "蓝色": ("blue", "#0000FF"),
        "靛色": ("indigo", "#4B0082"),
        "紫色": ("purple", "#800080"),
        "黑色": ("black", "#000000"),
        "白色": ("white", "#FFFFFF"),
        "灰色": ("gray", "#808080"),
        "棕色": ("brown", "#A52A2A"),
        "粉色": ("pink", "#FFC0CB"),
        "天蓝色": ("sky blue", "#87CEEB"),
        "湖蓝色": ("lake blue", "#00BFFF"),
        "蓝绿色": ("teal", "#008080"),
        "金色": ("gold", "#FFD700"),
        "银色": ("silver", "#C0C0C0"),
        "青铜色": ("bronze", "#CD7F32"),
        "玫瑰色": ("rose", "#FF69B4"),
        "珊瑚色": ("coral", "#FF7F50"),
        "紫罗兰色": ("violet", "#EE82EE"),
        "翡翠色": ("jade", "#20B2AA"),
        "土耳其蓝": ("turquoise", "#40E0D0"),
        "鲜红色": ("scarlet", "#FF2400"),
        "深红色": ("deep red", "#8B0000"),
        "朱红色": ("vermilion", "#D70040"),
        "猩红色": ("scarlet", "#DC143C"),
        "橙红色": ("orange red", "#FF4500"),
        "金黄色": ("golden yellow", "#FFD700"),
        "柠檬黄": ("lemon yellow", "#FFFACD"),
        "橄榄黄": ("olive yellow", "#98FB98"),
        "青绿色": ("cyan", "#00FFFF"),
        "墨绿色": ("dark green", "#006400"),
        "深绿色": ("forest green", "#228B22"),
        "浅绿色": ("light green", "#90EE90"),
        "宝石蓝": ("sapphire blue", "#1E90FF"),
        "深蓝色": ("dark blue", "#00008B"),
        "天空蓝": ("sky blue", "#87CEEB"),
        "海洋蓝": ("ocean blue", "#1E90FF"),
        "紫丁香色": ("lilac", "#DA70D6"),
        "深紫色": ("dark purple", "#9400D3"),
        "浅紫色": ("light purple", "#DDA0DD"),
        "薰衣草色": ("lavender", "#E6E6FA"),
        "洋红": ("magenta", "#FF00FF"),
        "品红": ("fuchsia", "#FF00FF"),
        "桃红": ("peach", "#FFB6C1"),
        "玫瑰红": ("rose", "#FF69B4"),
        "褐红色": ("sienna", "#A0522D"),
        "棕褐色": ("umber", "#8B4513"),
        "咖啡色": ("coffee", "#654321"),
        "巧克力色": ("chocolate", "#D2691E"),
        "焦糖色": ("caramel", "#FF7F50"),
        "奶油色": ("cream", "#FFFDD0"),
        "米色": ("beige", "#F5F5DC"),
        "象牙色": ("ivory", "#FFFFF0"),
        "玉色": ("jade", "#20B2AA"),
        "翠绿色": ("emerald green", "#50C878"),
        "碧绿色": ("turquoise green", "#40E0D0"),
        "孔雀蓝": ("peacock blue", "#4169E1"),
        "藏青色": ("navy blue", "#000080"),
        "海军蓝": ("navy blue", "#000080"),
        "皇家蓝": ("royal blue", "#4169E1"),
        "午夜蓝": ("midnight blue", "#191970"),
        "帝王紫": ("imperial purple", "#800080"),
        "东方紫": ("oriental purple", "#7F6000"),
        "波斯紫": ("persian purple", "#CC33CC"),
        "酒红色": ("wine red", "#800020"),
        "波尔多红": ("bordeaux", "#8B3A3A"),
        "印度红": ("indian red", "#CD5333"),
        "砖红色": ("brick red", "#B22222"),
        "火烈鸟粉": ("flamingo pink", "#FC6E4A"),
        "鲑鱼粉": ("salmon pink", "#FA8072"),
        "桃花粉": ("peach pink", "#FFDAB9"),
        "樱花粉": ("cherry blossom pink", "#FFB6C1"),
        "冰蓝色": ("ice blue", "#AFEEEE"),
        "冰晶蓝": ("glacier blue", "#AFEEEE"),
        "冰川蓝": ("glacier blue", "#AFEEEE"),
        "冰绿松石": ("turquoise", "#40E0D0"),
        "海蓝宝石蓝": ("aquamarine", "#7FE99F"),
        "翡翠绿": ("jade green", "#20B2AA"),
        "祖母绿": ("emerald green", "#50C878"),
        "苹果绿": ("apple green", "#A2CD5A"),
        "鳄梨绿": ("avocado green", "#50C878"),
        "浅海绿": ("aqua green", "#7FFF00"),
        "海藻绿": ("seaweed green", "#228B22"),
        "翡翠绿": ("jade green", "#20B2AA"),
        "孔雀绿": ("malachite green", "#40E0D0"),
        "绿松石": ("turquoise", "#40E0D0"),
        "青金石": ("lapis lazuli", "#483D8B"),
        "孔雀石": ("malachite", "#40E0D0"),
        "琥珀色": ("amber", "#FFBF00"),
        "蜂蜜色": ("honey", "#F5A623"),
        "沙棕色": ("sand brown", "#F4A460"),
        "骆驼色": ("camel", "#C19A6B"),
        "驼棕色": ("tan", "#D2B48C"),
        "灰褐色": ("taupe", "#A8B820"),
        "灰棕色": ("grey brown", "#BCBBBB"),
        "灰绿色": ("grey green", "#A9A9A9"),
        "灰蓝色": ("grey blue", "#BEBDBD"),
        "灰紫色": ("grey purple", "#CCC0C0"),
        "灰粉色": ("grey pink", "#D3D3D3"),
        "灰玉色": ("grey jade", "#B5B5B5"),
        "珍珠白": ("pearl white", "#F5F5F5"),
        "雪花白": ("snow white", "#FFFFFF"),
        "象牙白": ("ivory white", "#FFFFF0"),
        "米白色": ("off-white", "#F5F5DC"),
        "乳白色": ("milk white", "#FFFDD0")
    }
    return color_dict.get(color_name, None)


def get_color_info_en(color_name):
    """
    根据给定的颜色英文名称，返回对应的中文名称和十六进制颜色代码。
    
    参数：
    color_name (str): 颜色的英文名称
    
    返回：
    tuple: 包含颜色的中文名称和十六进制颜色代码的元组
    """
    color_dict = {
        "red": ("红色", "#FF0000"),
        "orange": ("橙色", "#FFA500"),
        "yellow": ("黄色", "#FFFF00"),
        "green": ("绿色", "#008000"),
        "blue": ("蓝色", "#0000FF"),
        "indigo": ("靛色", "#4B0082"),
        "purple": ("紫色", "#800080"),
        "black": ("黑色", "#000000"),
        "white": ("白色", "#FFFFFF"),
        "gray": ("灰色", "#808080"),
        "brown": ("棕色", "#A52A2A"),
        "pink": ("粉色", "#FFC0CB"),
        "sky blue": ("天蓝色", "#87CEEB"),
        "lake blue": ("湖蓝色", "#ADD8E6"),
        "teal": ("蓝绿色", "#008080"),
        "gold": ("金色", "#FFD700"),
        "silver": ("银白色", "#C0C0C0"),
        "bronze": ("青铜色", "#CD7F32"),
        "rose": ("玫瑰色", "#FF69B4"),
        "coral": ("珊瑚色", "#FF7F50"),
        "violet": ("紫罗兰色", "#EE82EE"),
        "jade": ("翡翠色", "#20B2AA"),
        "turquoise": ("土耳其蓝", "#40E0D0"),
        "scarlet": ("鲜红色", "#FF2400"),
        "deep red": ("深红色", "#8B0000"),
        "vermilion": ("朱红色", "#D70040"),
        "scarlet": ("猩红色", "#DC143C"),
        "orange red": ("橙红色", "#FF4500"),
        "golden yellow": ("金黄色", "#FFD700"),
        "lemon yellow": ("柠檬黄", "#FFFACD"),
        "olive yellow": ("橄榄黄", "#98FB98"),
        "cyan": ("青绿色", "#00FFFF"),
        "dark green": ("墨绿色", "#006400"),
        "forest green": ("深绿色", "#228B22"),
        "light green": ("浅绿色", "#90EE90"),
        "sapphire blue": ("宝石蓝", "#1E90FF"),
        "dark blue": ("深蓝色", "#00008B"),
        "sky blue": ("天空蓝", "#87CEEB"),
        "ocean blue": ("海洋蓝", "#1E90FF"),
        "lilac": ("紫丁香色", "#DA70D6"),
        "dark purple": ("深紫色", "#9400D3"),
        "light purple": ("浅紫色", "#DDA0DD"),
        "lavender": ("薰衣草色", "#E6E6FA"),
        "magenta": ("洋红", "#FF00FF"),
        "fuchsia": ("品红", "#FF00FF"),
        "peach": ("桃红", "#FFDAB9"),
        "rose": ("玫瑰色", "#FF69B4"),
        "sienna": ("褐红色", "#A0522D"),
        "umber": ("棕褐色", "#8B4513"),
        "coffee": ("咖啡色", "#654321"),
        "chocolate": ("巧克力色", "#D2691E"),
        "caramel": ("焦糖色", "#FF7F50"),
        "cream": ("奶油色", "#FFFDD0"),
        "beige": ("米色", "#F5F5DC"),
        "ivory": ("象牙色", "#FFFFF0"),
        "jade": ("玉色", "#20B2AA"),
        "emerald green": ("翠绿色", "#50C878"),
        "turquoise green": ("碧绿色", "#40E0D0"),
        "peacock blue": ("孔雀蓝", "#4169E1"),
        "navy blue": ("藏青色", "#000080"),
        "royal blue": ("皇家蓝", "#4169E1"),
        "midnight blue": ("午夜蓝", "#191970"),
        "imperial purple": ("帝王紫", "#800080"),
        "oriental purple": ("东方紫", "#7F6000"),
        "persian purple": ("波斯紫", "#CC33CC"),
        "wine red": ("酒红色", "#800020"),
        "bordeaux": ("波尔多红", "#8B3A3A"),
        "indian red": ("印度红", "#CD5333"),
        "brick red": ("砖红色", "#B22222"),
        "flamingo pink": ("火烈鸟粉", "#FC6E4A"),
        "salmon pink": ("鲑鱼粉", "#FA8072"),
        "peach pink": ("桃花粉", "#FFDAB9"),
        "cherry blossom pink": ("樱花粉", "#FFB6C1"),
        "ice blue": ("冰蓝色", "#AFEEEE"),
        "glacier blue": ("冰川蓝", "#AFEEEE"),
        "aquamarine blue": ("碧蓝色", "#7FE99F"),
        "aqua green": ("海藻绿", "#228B22"),
        "seaweed green": ("海绿色", "#228B22"),
        "jade green": ("玉绿色", "#20B2AA"),
        "malachite green": ("孔雀绿", "#40E0D0"),
        "turquoise": ("绿松石", "#40E0D0"),
        "lapis lazuli": ("青金石", "#483D8B"),
        "malachite": ("孔雀石", "#40E0D0"),
        "amber": ("琥珀色", "#FFBF00"),
        "honey": ("蜂蜜色", "#F5A623"),
        "sand brown": ("沙棕色", "#F4A460"),
        "camel": ("骆驼色", "#C19A6B"),
        "tan": ("棕褐色", "#C19A6B"),
        "taupe": ("灰褐色", "#A8B820"),
        "grey brown": ("灰棕色", "#BCBBBB"),
        "grey green": ("灰绿色", "#A9A9A9"),
        "grey blue": ("灰蓝色", "#BEBDBD"),
        "grey purple": ("灰紫色", "#CCC0C0"),
        "grey pink": ("灰粉色", "#D3D3D3"),
        "grey jade": ("灰玉色", "#B5B5B5"),
        "pearl white": ("珍珠白", "#F5F5F5"),
        "snow white": ("雪花白", "#FFFFFF"),
        "ivory white": ("象牙白", "#FFFFF0"),
        "off-white": ("米白色", "#F5F5DC"),
        "milk white": ("乳白色", "#FFFDD0")
    }
    return color_dict.get(color_name, (None, None))



def cmd(command):
    """
    运行给定的Linux命令并返回输出结果

    参数：
    command (str): 要运行的Linux命令

    返回：
    str: 命令的输出结果
    """
    import subprocess

    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
    return result.stdout.strip()


def classify_files(src_dir):
    """
    根据扩展名对文件分类
    :param src_dir，要分类文件所在的目录
    """
    categories={         #根据需要，可以添加更多分类
        'txt':'Text Files',
        'doc':'Doc Files',
        'pdf':'Pdf Files',
        'xls':'Excel Files',
        'docx':'Doc Files',
        'png':'Images',
        'bmp':'Images',
        'jpg':'Images',
        'jpeg':'Images',
        'tiff':'Images',
        'ppm':'Images',
        'gif':'Images'
        }

    # 遍历源目录中的所有文件 
    for filename in os.listdir(src_dir): 
        # 获取文件扩展名 
        _, ext = os.path.splitext(filename) 
        ext = ext.lower().lstrip('.') # 去除'.'并转换为小写

        # 根据扩展名进行分类 
        if ext in categories: 
            category_dir = os.path.join(src_dir, categories[ext]) 
            if not os.path.exists(category_dir): 
                os.makedirs(category_dir) # 如果分类目录不存在，则创建它 
                # 移动文件到相应的分类目录 
            src_file = os.path.join(src_dir, filename) 
            dst_file = os.path.join(category_dir, filename) 
            shutil.move(src_file, dst_file) 
        else: 
            print(f"无法识别的文件扩展名: {filename}")

def modify_name(src_dir,old_name,new_name): 
    """
    更改指定的文件名
    :param src_dir,文件目录
    :param old_name，旧文件名
    :param new_name，新文件名
    """
    if not os.path.exists(src_dir): 
        print('文件路径不正确，请检查') 
    else: 
        file_list = os.listdir(src_dir) # 获取目录下的文件 
        #print('list', file_list) 
        for i in file_list: # 去掉打开的临时文件 
            if i.startswith('~$'): continue 
            # 修改文件名 
            new_file = i.replace(old_name, new_name) 
            src_file = os.path.join(src_dir, i) # 源路径 
            dst_file = os.path.join(src_dir, new_file) # 目标路径 
            os.rename(src_file, dst_file)











